#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : Wed Jul 17 2019
# @Author  : xujunfu (xjf891121@gmail.com})
# @Link    : http://junfuxu.github.io/

from .base import XZBaseHandler


class TerminalHandler(XZBaseHandler):

    def __init__(self, *args, **kwargs):
        self.imei2vehicle_info_map = {}
        for k, v in self.vin2vehicle_map.items():
            self.imei2vehicle_info_map[v['imei']] = v
        super().__init__(*args, **kwargs)

    def register(self, data):
        # {'iccid': '89861118243038672550', 'curModelCode': '10', 'terminalId': '861290030045012', 'rom': 'V1.0.4', 'version': '2031'}
        # {'terminalId': '861290030041151', 'rom': 'V1.0.2', 'curModelCode': '10', 'version': '2028'}
        terminal_id = data['terminalId']
        if terminal_id in self.imei2vehicle_info_map:  # 找到terminal_id, 已经注册过
            return self.imei2vehicle_info_map[terminal_id]
        self.logger.info(data)
        # 向后台新加
        res = self.yb_api.add_xz_vehicle({
            "vehicle": {
                "license_number": '0000000',
                "vin": terminal_id,
            },
            "company": {
                "name": '开易'  # 新车辆同一配置给开易公司名下
            },
            "terminal": {
                "imei": terminal_id,
                "iccid": data.get('iccid', None),
                'hardware_version': data["rom"],
                'firmware_version': data["version"],
                'device_type': 'YB'
            }
        }).json()

        # 更新映射表
        self.vin2vehicle_map[res['vehicle']['vin']] = {
            'terminal_id': res['terminal']['id'],
            'vehicle_id': res['vehicle']['id'],
            'company_id': res['company']['id'],
            'license_number': res['vehicle']['license_number'],
            'vin': res['vehicle']['vin'],
            'device_id': res['terminal']['imei'],
            'imei': res['terminal']['imei']
        }
        return res
